import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/tally/tallyskuscreen.dart';
import 'package:toast/toast.dart';

import 'tallymodel.dart';

class TallyScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return TallyScreenPage();
  }
}

class TallyScreenPage extends StatefulWidget {
  @override
  _TallyScreenPageState createState() => _TallyScreenPageState();
}

class _TallyScreenPageState extends BaseState<TallyScreenPage> {
  final TextEditingController dateController = TextEditingController();
  final controller = ScrollController();

  int index = 0, position;
  List<Tally> data = new List();
  List<Tally> dataAll = new List();
  List<TallyDetail> tallyDetails = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Tally:Container";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        getTallyContainerNo();
      });
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 0, top: 10, right: 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(left: 15, top: 5, right: 15, bottom: 0),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 40),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 25,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        print(text); //拿到扫描结果
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "input container number",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                  setSearchData();
                },
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 10, left: 15, right: 15),
            child: Row(
              children: [
                Expanded(
                  flex: 1, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());
                      if (type == 1) {
                        return;
                      }
                      setState(() {
                        type = 1;
                        textEditingController.text = "";
                        data.clear();
                        getTallyContainerNo();
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.all(5),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                        borderRadius: BorderRadius.only(topLeft: Radius.circular(8.0), bottomLeft: Radius.circular(8.0)), // 圆角半径
                        border: Border.all(
                          color: MyAppTheme.nearlyBlue, // 边框颜色
                          width: 0.5, // 边框宽度
                        ),
                      ),
                      child: Text(
                        'Tallying',
                        style: type == 1 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                      ), // 子控件，如果需要的话
                    ),
                  ),
                ),
                Expanded(
                  flex: 1, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());
                      if (type == 2) {
                        return;
                      }
                      setState(() {
                        type = 2;
                        textEditingController.text = "";
                        data.clear();
                        getTallyContainerNo();
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.all(5),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                        borderRadius: BorderRadius.only(topRight: Radius.circular(8.0), bottomRight: Radius.circular(8.0)), // 圆角半径
                        border: Border.all(
                          color: MyAppTheme.nearlyBlue, // 边框颜色
                          width: 0.5, // 边框宽度
                        ),
                      ),
                      child: Text(
                        'Completed',
                        style: type == 2 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                      ), // 子控件，如果需要的话
                    ),
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.only(left: 15, right: 10, top: 10),
              child: setListView(),
            ),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        Tally tally = data[index];
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                  flex: 2, //设置权重
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            Utils.getStringisEmpty(tally.containerNo),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                          ),
                          SizedBox(width: 5,),
                          Visibility(
                            visible: tally.status == 'RETALLY' ? true : false,
                            child: Text(
                              'retallying',
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(color: MyAppTheme.red, fontSize: 10.0),
                            ),
                          ),
                        ],
                      ),
                      Visibility(
                        visible: !Utils.isEmpty(tally.inboundNo),
                        child: Text(
                          Utils.getStringisEmpty(tally.inboundNo),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                        ),
                      ),
                    ],
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    getWarehousingDetailTallyInfo(tally);
                  },
                  child: Container(
                    margin: EdgeInsets.only(left: 5, right: 10),
                    child: Image.asset(
                      'assets/images/details.png',
                      width: 20,
                      height: 20,
                    ),
                  ),
                ),
                Visibility(
                  visible: type == 1 ? true : false,
                  child: GestureDetector(
                    onTap: () {
                      TallyQr tallyQr = TallyQr.name(tally.id, tally.containerNo, tally.inboundNo, tally.id, type, tally.status);
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => TallySkuScreen(data: tallyQr)),
                      ).then((value) => {
                        if (value != null && value)
                          {
                            setState(() {
                              getTallyContainerNo();
                            })
                          }
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.all(3),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: MyAppTheme.nearlyBlue, // 背景颜色
                        borderRadius: BorderRadius.all(Radius.circular(5)), // 圆角半径
                        border: Border.all(
                          color: MyAppTheme.nearlyBlue, // 边框颜色
                          width: 0.5, // 边框宽度
                        ),
                      ),
                      child: Text(
                        'Tally',
                        style: MyAppTheme.captionWhite,
                      ), // 子控件，如果需要的话
                    ),
                  ),
                ),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  @override
  void setNext() {
    ToastContext().init(context);
    // if (Utils.isEmpty(strDate)) {
    //   Toast.show("Please select Drop Date", duration: Toast.lengthShort, gravity: Toast.bottom);
    //   return;
    // }
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
    });
  }

  void getTallyContainerNo() async {
    String url = Constants.getTallyContainerNo;
    if (type == 2) {
      url = Constants.getTallyFinishContainerNo;
    }
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    BaseResponse baseResponse = await NetworkManager().request(context, url);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        dataAll = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => Tally.fromJson(userJson)).toList());
        data.clear();
        data.addAll(dataAll);
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void getWarehousingDetailTallyInfo(Tally tally) async {
    String url = Constants.getTallyDetail;
    if (type == 2) {
      url = Constants.getTallyFinishDetail;
    }

    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }

    Map<String, dynamic> map = new HashMap();
    map["warehousingNotifyId"] = tally.id;
    BaseResponse baseResponse = await NetworkManager().request(context, url, params: map);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      tallyDetails = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => TallyDetail.fromJson(userJson)).toList());
      String result = await showDialog(
        context: context,
        builder: (context) => CustomDialog(tally: tally, tallyDetails: tallyDetails),
      );
      if(Utils.getStringisEmpty(result)=="ok"){
        setState(() {
          getTallyContainerNo();
        });
      }
      print("result:${result}");
      // setState(() {
      //   tallyDetails = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => TallyDetail.fromJson(userJson)).toList());
      //   showDialog(
      //     context: context,
      //     builder: (context) => CustomDialog(tally: tally, tallyDetails: tallyDetails),
      //   );
      // });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void setSearchData() {
    if (dataAll.length == 0) {
      return;
    }
    setState(() {
      if (Utils.isEmpty(code)) {
        data.clear();
        data.addAll(dataAll);
      } else {
        data.clear();
        dataAll.forEach((tally) {
          if (tally.containerNo.toLowerCase().contains(code.toLowerCase())) {
            data.add(tally);
          }
        });
      }
    });
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }
}

class CustomDialog extends StatefulWidget {
  Tally tally;
  List<TallyDetail> tallyDetails = new List();

  CustomDialog({this.tally, this.tallyDetails});

  @override
  _CustomDialogState createState() => _CustomDialogState(tally: tally, tallyDetails: this.tallyDetails);
}

class _CustomDialogState extends State<CustomDialog> {
  Tally tally;
  List<TallyDetail> tallyDetails = new List();

  _CustomDialogState({this.tally, this.tallyDetails});

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12.0),
      ),
      child: Padding(
        padding: const EdgeInsets.only(top: 15, left: 15, right: 15),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text("Detail(${tally.containerNo})", style: MyAppTheme.title),
            SizedBox(height: 16.0),
            Row(
              children: [
                Expanded(
                    flex: 2,
                    child: Text(
                      'SKU',
                      style: MyAppTheme.text,
                    )),
                Expanded(flex: 1, child: Text('Tallied', style: MyAppTheme.text)),
                Expanded(flex: 1, child: Text('lpnQTY', style: MyAppTheme.text)),
                SizedBox(width: 20.0),
              ],
            ),
            Flexible(
              fit: FlexFit.loose,
              child: setListView(),
            ),
            // Expanded(
            //   child: setListView(),
            // ),
            // setListView(),
            // SizedBox(height: 5.0),
            Row(
              children: <Widget>[
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Close',
                        style: MyAppTheme.title,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    )),
                Visibility(
                  visible: ((tally.type == 1) && (!tally.status.contains("TALLIED"))) ? true : false,
                  child: Expanded(
                      flex: 1,
                      child: FlatButton(
                        child: Text(
                          'Confirm',
                          style: MyAppTheme.titlenearlyBlue16,
                        ),
                        onPressed: () {
                          fbaCompleted(tally.id);
                        },
                      )),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      shrinkWrap: true,
      // physics: NeverScrollableScrollPhysics(),
      itemCount: tallyDetails == null ? 0 : tallyDetails.length,
      itemBuilder: (context, index) {
        TallyDetail tallyDetail = tallyDetails[index];
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                    flex: 2,
                    child: Text(
                      tallyDetail.sku,
                      style: MyAppTheme.text,
                    )),
                Expanded(flex: 1, child: Text('${tallyDetail.tallyQty}', style: MyAppTheme.text)),
                Expanded(flex: 1, child: Text('${tallyDetail.lpnQty}', style: MyAppTheme.text)),
                GestureDetector(
                  onTap: () {
                    setState(() {
                      if (tallyDetail.list == null || tallyDetail.list.length == 0) {
                        getLpnQtyList(tally.id, tallyDetail, index);
                        return;
                      }
                      tallyDetail.click = !tallyDetail.click;
                    });
                  },
                  child: Icon(
                    tallyDetail.click ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                    size: 20,
                    color: MyAppTheme.nearlyBlue,
                  ),
                ),
              ],
            ),
            Visibility(visible: tallyDetail.click ? true : false, child: setListViewItem(tallyDetail.list)),
            // Expanded(
            //   child: Visibility(visible: tally.click, child: setListViewItem(tally.list)),
            // ),
            Divider(),
          ],
        );
      },
    );
  }

  ListView setListViewItem(List<Lpns> list) {
    return ListView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: list == null ? 0 : list.length,
      itemBuilder: (context, index) {
        Lpns lpnBean = list[index];
        return Row(
          children: [
            SizedBox(
              width: 10,
            ),
            Expanded(
                flex: 2,
                child: Text(
                  Utils.getStringisEmpty(lpnBean.lpn),
                  style: MyAppTheme.test12,
                )),
            Expanded(flex: 1, child: Text('${lpnBean.inventory}', style: MyAppTheme.test12)),
            Visibility(
              visible: Utils.isEmpty(lpnBean.type) ? false : (lpnBean.type == 'good' ? false : true),
              child: Image.asset(
                'assets/images/home/ic_home_damage.png',
                width: 20,
                height: 20,
              ),
            ),
            Visibility(
              visible: Utils.isEmpty(lpnBean.type) ? true : (lpnBean.type == 'good' ? true : false),
              child: SizedBox(
                width: 20,
              ),
            ),
          ],
        );
      },
    );
  }

  void getLpnQtyList(int id, TallyDetail tallyDetail, int position) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }

    Map<String, dynamic> map = new HashMap();
    map["warehousingNotifyId"] = id;
    map["sku"] = tallyDetail.sku;
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.getTallySkuDetail, params: map);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        tallyDetail.list = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => Lpns.fromJson(userJson)).toList());
        tallyDetail.click = true;
        tallyDetails[position] = tallyDetail;
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
  void fbaCompleted(int id) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context,title: "submint");
    } catch (e) {
      e.toString();
    }

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.fbaCompleted+"/${id}",method: BaseMethod.put);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      Navigator.of(context).pop('ok');
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
}
